/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.cspimp.em.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.cspimp.em.domain.Exercise;
import me.zhengjie.modules.cspimp.em.domain.vo.ExerciseVo;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.em.repository.ExerciseRepository;
import me.zhengjie.modules.cspimp.em.service.ExerciseService;
import me.zhengjie.modules.cspimp.em.service.dto.ExerciseDto;
import me.zhengjie.modules.cspimp.em.service.dto.ExerciseQueryCriteria;
import me.zhengjie.modules.cspimp.em.service.mapstruct.ExerciseMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://docs.auauz.net
* @description 服务实现
* @author zmm
* @date 2020-05-24
**/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ExerciseServiceImpl implements ExerciseService {

    private final ExerciseRepository exerciseRepository;
    private final ExerciseMapper exerciseMapper;

    @Override
    public Map<String,Object> queryAll(ExerciseQueryCriteria criteria, Pageable pageable){
        Page<Exercise> page = exerciseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(exerciseMapper::toDto));
    }

    @Override
    public List<ExerciseDto> queryAll(ExerciseQueryCriteria criteria){
        return exerciseMapper.toDto(exerciseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public ExerciseDto findById(Long id) {
        Exercise exercise = exerciseRepository.findById(id).orElseGet(Exercise::new);
        ValidationUtil.isNull(exercise.getId(),"Exercise","id",id);
        return exerciseMapper.toDto(exercise);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExerciseDto create(ExerciseVo resources) {
        String title = resources.getExerciseTitle();
        String isNotive = resources.getIsNotive();
        Integer hour = resources.getAdvanceHour();
        if (isNotive.equals("1")) {
            if (null == hour) {
                throw new BadRequestException("通知打开，必须填入提前时间");
            }
            isNotive="开启";
        }else {
            isNotive="关闭";
        }
        if (exerciseRepository.findByExerciseTitle(title) != null) {
            throw new EntityExistException(Exercise.class, "exerciseTitle", resources.getExerciseTitle());
        }
        Exercise exercise = new Exercise();
//        Date exerciseDate = null;
//        try {
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//            exerciseDate = sf.parse(resources.getExerciseDate());
//        } catch (Exception e) {
//
//        }
        String exerciseDate=resources.getExerciseDate();
        if(StringUtils.isBlank(exerciseDate)){
            throw new BadRequestException("演练时间不能为空");
        }
        exercise.setExerciseDate(exerciseDate);
        exercise.setCid(0l);
        exercise.setAdvanceHour(hour == null ? 0 : hour);
        exercise.setExerciseTitle(title);
        exercise.setExerciseObjective(resources.getExerciseObjective());
        exercise.setExerciseProcess(resources.getExerciseProcess());
        exercise.setIsNotive(isNotive);
        return exerciseMapper.toDto(exerciseRepository.save(exercise));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ExerciseVo resources) {
        String title = resources.getExerciseTitle();
        Exercise exercise = exerciseRepository.findById(resources.getId()).get();
        ValidationUtil.isNull(exercise.getId(), "Exercise", "id", resources.getId());
        String isNotive = resources.getIsNotive();
        Integer hour = resources.getAdvanceHour();
        if (isNotive.equals("开启")) {
            if (null == hour) {
                throw new BadRequestException("通知打开，必须填入提前时间");
            }
        }
        Exercise c = exerciseRepository.findByExerciseTitle(title);

        if (c != null && !c.getId().equals(c.getId())) {
            throw new EntityExistException(Exercise.class, "exerciseTitle", title);
        }
//        Date exerciseDate = null;
//        try {
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//            exerciseDate = sf.parse(resources.getExerciseDate());
//        } catch (Exception e) {
//        }
        String exerciseDate=resources.getExerciseDate();
        if(StringUtils.isBlank(exerciseDate)){
            throw new BadRequestException("演练时间不能为空");
        }
        exercise.setExerciseDate(exerciseDate);
        exercise.setCid(0l);
        exercise.setAdvanceHour(hour == null ? 0 : hour);
        exercise.setExerciseTitle(title);
        exercise.setExerciseObjective(resources.getExerciseObjective());
        exercise.setExerciseProcess(resources.getExerciseProcess());
        exercise.setIsNotive(isNotive);
        exerciseRepository.save(exercise);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            exerciseRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ExerciseDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ExerciseDto exercise : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" cid",  exercise.getCid());
            map.put("演练目的", exercise.getExerciseObjective());
            map.put("演练流程", exercise.getExerciseProcess());
            map.put("公告通知状态", exercise.getIsNotive());
            map.put("演练时间", exercise.getExerciseDate());
            map.put("通知提前小时", exercise.getAdvanceHour());
            map.put("应急演练标题", exercise.getExerciseTitle());
            map.put("创建时间", exercise.getCreateTime());
            map.put("更新时间", exercise.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}